import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        System.out.println(new Solution().allPathsSourceTarget(new int[][]{{1, 2}, {3}, {3}, {}}));
        System.out.println(new Solution().allPathsSourceTarget(new int[][]{{4,3,1}, {3,2,4}, {3},{4},{}}));
    }
}

class Solution {
    public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
        List<List<Integer>> result = new ArrayList<>();
        Deque<Integer> path = new ArrayDeque<>();
        path.addLast(0);
        dfs(graph, path, result);
        return result;
    }

    private void dfs(int[][] graph, Deque<Integer> path, List<List<Integer>> result) {
        int cur = path.peekLast();
        if (cur == graph.length - 1) {
            result.add(new ArrayList<>(path));
            return;
        }

        for (int next : graph[cur]) {
            path.addLast(next);
            dfs(graph, path, result);
            path.removeLast();
        }
    }
}